package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.hmdp.utils.CacheManager;
import com.hmdp.utils.RedisData;
import com.hmdp.utils.SystemConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.geo.*;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private CacheManager cacheManager;

    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);


    /**
     * 根据id查询店铺信息
     *
     * @param id 店铺id
     * @return 结果
     */
    @Override
    public Result queryById(Long id) {
        // 缓存穿透-存储NULL
        // Shop = cacheManager.queryWithPassThrough(CACHE_SHOP_KEY, id, Shop.class, CACHE_SHOP_TTL, TimeUnit.MINUTES, this::getById);

        // 缓存击穿-互斥锁
        // Shop = queryWithMutex(id);

        // 缓存击穿-逻辑过期
        Shop shop = cacheManager.queryWithLogicalExpire(CACHE_SHOP_KEY, id, Shop.class,
                LOCK_SHOP_KEY + id, CACHE_SHOP_TTL, TimeUnit.SECONDS, this::getById);
        return Result.ok(shop);
    }


    /**
     * 查询商铺信息
     * 缓存击穿-互斥锁
     *
     * @param id 店铺id
     * @return 店铺信息
     */
    public Shop queryWithMutex(Long id) {
        // 1 从Redis查询商铺缓存
        String key = CACHE_SHOP_KEY + id;
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        if (StringUtils.isNotBlank(shopJson)) {
            // 1.1 命中缓存，返回结果
            if (CACHE_NULL.equals(shopJson)) {
                throw new RuntimeException("缓存NULL，商户信息不存在");
            } else {
                return JSONUtil.toBean(shopJson, Shop.class);
            }
        }

        // 2 Redis未命中，尝试获取互斥锁
        try {
            boolean isLock = tryLock(LOCK_SHOP_KEY + id);
            if (!isLock) {
                // 2.1 获取锁失败，进行休眠重试(递归)
                Thread.sleep(50);
                return queryWithMutex(id);
            } else {
                // 2.2 获取锁成功，但需要进行二次缓存确定，然后进行查询数据库
                Shop byId = getById(id);
                // 模拟重建热点key的延时
                Thread.sleep(200);
                if (byId == null) {
                    // 不存在，将空值存入缓存
                    stringRedisTemplate.opsForValue().set(key, "null", CACHE_NULL_TTL, TimeUnit.MINUTES);
                    throw new RuntimeException("数据库NULL，商户信息不存在");
                } else {
                    // 存在，存入数据
                    stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(byId), CACHE_SHOP_TTL, TimeUnit.MINUTES);
                    return byId;
                }
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            // 3. 释放互斥锁
            unLock(LOCK_SHOP_KEY + id);
        }
    }


    /**
     * 加互斥锁
     * 一般互斥锁的过期时间要比业务所需重构缓存时间长一点即可
     *
     * @param key 锁名
     * @return 加锁结果
     */
    private boolean tryLock(String key) {
        return Boolean.TRUE.equals(stringRedisTemplate.opsForValue().setIfAbsent(key, "lock", LOCK_SHOP_TTL, TimeUnit.SECONDS));
    }


    /**
     * 释放互斥锁
     *
     * @param key 锁名
     */
    private void unLock(String key) {
        stringRedisTemplate.delete(key);
    }


    /**
     * 更新店铺信息
     * 加事务，防止缓存与数据库数据不一致（数据库更改成功但是缓存未删除为旧数据）
     *
     * @param shop 店铺信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public Result updateShop(Shop shop) {
        // 参数校验
        if (shop.getId() == null) {
            return Result.fail("店铺id为空!");
        }
        // 先更新数据库
        this.updateById(shop);
        // 再删除缓存
        stringRedisTemplate.delete(CACHE_SHOP_KEY + shop.getId());

        return Result.ok();
    }

    /**
     * 根据店铺类型查询店铺信息
     *
     * @param typeId  店铺类型id
     * @param current 当前页
     * @param x       经度
     * @param y       纬度
     * @return 结果
     */
    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        // 是否需要根据坐标查询
        if (x == null || y == null) {
            // 根据类型分页查询
            Page<Shop> page = query()
                    .eq("type_id", typeId)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            // 返回数据
            return Result.ok(page.getRecords());
        }

        // 计算分页参数
        int from = (current - 1) * SystemConstants.DEFAULT_PAGE_SIZE;
        int end = current * SystemConstants.DEFAULT_PAGE_SIZE;

        // 查询Redis，得到 ShopId、distance
        String key = GEO_SHOP_TYPE_KEY + typeId;
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo()
                .search(key, GeoReference.fromCoordinate(new Point(x, y)),
                        new Distance(5000),
                        RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs()
                                .includeDistance()
                                .limit(end));
        if (results == null) {
            return Result.ok(Collections.emptyList());
        }
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent();
        if (list.size() <= from) {
            // 没有下一页了，结束
            return Result.ok(Collections.emptyList());
        }
        // 4.1.截取 from ~ end的部分
        List<Long> ids = new ArrayList<>(list.size());
        Map<String, Distance> distanceMap = new HashMap<>(list.size());
        list.stream().skip(from).forEach(result -> {
            // 4.2.获取店铺id
            String shopIdStr = result.getContent().getName();
            ids.add(Long.valueOf(shopIdStr));
            // 4.3.获取距离
            Distance distance = result.getDistance();
            distanceMap.put(shopIdStr, distance);
        });
        // 5.根据id查询Shop
        String idStr = StrUtil.join(",", ids);
        List<Shop> shops = query().in("id", ids).last("ORDER BY FIELD(id," + idStr + ")").list();
        for (Shop shop : shops) {
            shop.setDistance(distanceMap.get(shop.getId().toString()).getValue());
        }
        // 6.返回
        return Result.ok(shops);
    }
}
